﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using System.Windows.Interactivity;

namespace Ops.Mpc.States
{
    public class DoubleClickTrigger : TriggerBase<UIElement>
    {
        private readonly DispatcherTimer _timer;

        public DoubleClickTrigger()
        {
            _timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(300)
            };
            _timer.Tick += OnTimerTick;
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(OnMouseAction), true);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.RemoveHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(OnMouseAction));
            if (_timer.IsEnabled)
            {
                _timer.Stop();
            }
        }

        private void OnMouseAction(object sender, MouseButtonEventArgs e)
        {
            if (!_timer.IsEnabled)
            {
                _timer.Start();
                return;
            }

            _timer.Stop();
            DoInvoke();
        }

        private void OnTimerTick(object sender, EventArgs e)
        {
            _timer.Stop();
        }

        protected virtual void DoInvoke()
        {
            FrameworkElement frameworkElement = this.AssociatedObject as FrameworkElement;

            if (frameworkElement != null)
                InvokeActions(frameworkElement.DataContext);
            else
                InvokeActions(this.AssociatedObject);
        }


    }

}
